package com.my.ddd_sample_collections.aggregate_change_tracking.repository_framework;

import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.*;

public class DomainObjectUtils {
    public static void deepMarkUnchanged(DomainObject root) {

        Class<?> currentEntityClass = root.getClass();
        DomainObject currentObject = root;

        markUnchanged( currentObject);

        while (DomainObject.class.isAssignableFrom(currentEntityClass)) {
            for (Field field : currentEntityClass.getDeclaredFields()) {

                Type declaringType = field.getGenericType();
                field.setAccessible(true);
                if (declaringType instanceof Class) {
                    if (!ReflectionUtils.isJdkPrimitiveType(((Class) declaringType))
                            && DomainObject.class.isAssignableFrom((Class) declaringType)) {
                        try {
                            currentObject = (DomainObject) field.get(currentObject);
                        } catch (IllegalAccessException e) {
                            throw new RuntimeException(e);
                        }
                        markUnchanged(currentObject);
                    }
                }
            }
            currentEntityClass = currentEntityClass.getSuperclass();
        }
    }

    private static void markUnchanged(DomainObject entity) {
        entity.markUnchanged();
    }
    
    public static void setPOVersions(AggregateRoot root, PersistenceObject... pos) {
        //TODO 构造poVersionMap，并设置到root中
        Map<String, Integer> versionsMap = null;
        root.setPersistenceObjectVersions(versionsMap);
    }
    
    public static void setPOVersions(AggregateRoot root, List<? extends PersistenceObject> items, PersistenceObject... pos) {
        assert items!=null;
        assert pos!=null;
        List<PersistenceObject> all = new ArrayList<>(items);
        all.addAll(List.of(pos));
        setPOVersions(root, all.toArray(all.toArray(new PersistenceObject[0])));
    }
}
